from functools import wraps
from flask import jsonify, request
from common.status_code import Status
import service
import hashlib
from common.configration import ConfigHelper, ConfigSections, ConfigKeys

def check_auth(username="", password=""):
    service.app.logger.debug("[Debug] Invoke method: check_auth(username={0}, password={1})".format(username, password));
    
    if (len(username) > 0) and (len(password) > 0):
        # Read correct user name and password from web.conf file
        conf = ConfigHelper();
        correct_username = conf.get_instance().get(ConfigSections.auth, ConfigKeys.user);
        correct_encrypted_pwd = conf.get_instance().get(ConfigSections.auth, ConfigKeys.encrypted_password);
        
        service.app.logger.debug("[Debug] web.conf => [auth]user={0} encrypted_password={1}".format(correct_username, correct_encrypted_pwd));
        
        encrypted_pwd = str(hashlib.sha256(password).hexdigest());
        if username == correct_username and encrypted_pwd == correct_encrypted_pwd:
            return True;
        
    return False;

def permission_denied(message="Access denied."):
    data = {'status': Status.ACCESS_DENIED, 'message': message}
    resp = jsonify(data)

    resp.status_code = 401
    resp.headers['WWW-Authenticate'] = 'Basic realm="Taxi Reservation Service"'

    return resp

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        service.app.logger.debug("request.authorization={0}".format(str(auth)));
        
        if not auth: 
            return permission_denied()

        elif not check_auth(auth.username, auth.password):
            return permission_denied("Incorrect user name or password.")
        
        return f(*args, **kwargs)

    return decorated
